package org.example.domain.activity.service.quota.rule.chain.impl;

import lombok.extern.slf4j.Slf4j;
import org.example.domain.activity.model.entity.ActivityCountEntity;
import org.example.domain.activity.model.entity.ActivityEntity;
import org.example.domain.activity.model.entity.ActivitySkuEntity;
import org.example.domain.activity.model.valobj.SubtractionSkuStockMessageVO;
import org.example.domain.activity.repository.IActivityRepository;
import org.example.domain.activity.service.quota.rule.chain.AbstractActionChain;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 责任链单个节点: sku库存扣减
 */
@Slf4j
@Component("activity_sku_stock_action")
public class ActivitySkuStockActionChain extends AbstractActionChain {


    @Resource
    private IActivityRepository  activityRepository;

    /**
     * 在redis中扣减库存并发送消息通知mysql库存扣减
     * @param activitySkuEntity  活动sku实体
     * @param activityEntity 活动实体
     * @param activityCountEntity 一次活动账户增长次数实体
     * @return
     */
    @Override
    public Boolean action(ActivitySkuEntity activitySkuEntity, ActivityEntity activityEntity, ActivityCountEntity activityCountEntity,String userId) {
        log.info("活动责任链-商品库存处理【校验&扣减】开始。");

        Long sku = activitySkuEntity.getSku();
        boolean state = activityRepository.subtractionSkuStockFromRedis(sku,activityEntity.getEndDateTime());//第二个参数是为了给加库存流水锁加失效时间

        if (state){
            log.info("redis中sku_stock扣减成功,接下来发送消息");
            activityRepository.sendSubtractionSkuStockMessage(SubtractionSkuStockMessageVO.builder()
                    .activityId(activityEntity.getActivityId())
                    .sku(activitySkuEntity.getSku())
                    .build(), sku);
            return true;
        }

        log.info("redis_sku_stock库存扣减失败");
        return false;
    }
}
